<template>
  <div class="menu-wrap">
    <el-menu
      :default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      @select="handleSelect"
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#409EFF">
      <el-submenu v-for="(item,index) in navMenu" :index="item.index" :key="index">
        <template slot="title">{{item.title}}</template>
        <el-menu-item v-for="(__item,__index) in item.subM" :index="__item.index" :key="__index">{{__item.title}}</el-menu-item>
      </el-submenu>
    </el-menu>
  </div>
</template>
<script>
export default {
  name:'nav-menu-horizontal',
  data(){
    return {
      activeIndex:this.$store.state.basicInfo.navMenuIndex
    }
  },
  computed:{
    navMenu(){
      return this.$store.state.basicInfo.navMenu
    },
    // 获取所有子菜单
    subMenu(){
      return this.$store.state.basicInfo.subMenu
    }
  },
  mounted(){

  },
  methods:{
    handleSelect(key){
      // 获取当前活动菜单的信息
      let result = this.subMenu.find((item)=>{
        return item.index === key
      })
      let {id,title,route,index} = result
      this.$store.commit('setMenuTag',{id,title,route,index}) // 把当前活动的菜单添加到vuex的menuTag数组中（setMenuTag方法已包含去重判断）
      this.$store.commit('setNavMenuIndex',index) // 设置当前激活菜单的 index
      this.$router.push({name:route.substring(1)})
    }
  },
  watch:{
    // 监听vuex中navMenuIndex的变化，设置当前菜单激活项
    '$store.state.basicInfo.navMenuIndex':function(){
      this.activeIndex = this.$store.state.basicInfo.navMenuIndex
    }
  }
}
</script>
<style lang="scss" scoped>
.menu-wrap{display: flex;}
</style>